package service

import (
	"beego-admin/models"
)

type HomeInfoJson struct {
	Title string	`json:"title"`
	Href string		`json:"href"`
}
type LogoInfoJson struct {
	Title string	`json:"title"`
	Href string		`json:"href"`
	Image string	`json:"image"`
}

type LeftMenuJson struct {
	HomeInfo HomeInfoJson	`json:"homeInfo"`
	LogoInfo LogoInfoJson	`json:"logoInfo"`
	MenuInfo	[]*TreeList  `json:"menuInfo"`
}

type Menu struct {
	Id int 			`json:"id"`
	Title string			`json:"title"`
	Icon string 	`json:"icon"`
	Href string 		`json:"href"`
	Target string	`json:"target"`
}

type TreeList struct {
	Id int			`json:"id"`
	Title string			`json:"title"`
	Icon string 	`json:"icon"`
	Href string 		`json:"href"`
	Target string	`json:"target"`
	Child []*TreeList	`json:"child"`
}

type MenuList struct{
	AuthorityId int `json:"authorityId"`
	AuthorityName string `json:"authorityName"`
	OrderNumber int `json:"orderNumber"`
	MenuUrl string `json:"menuUrl"`
	MenuIcon string `json:"menuIcon"`
	IsMenu int `json:"isMenu"`
	ParentId int `json:"parentId"`
	MenuType string `json:"menu_type"`
}

type AuthTreeList struct {
	Id int			`json:"id"`
	Title string			`json:"title"`
	Checked bool 	`json:"checked"`
	Spread bool 		`json:"spread"`
	Children []*AuthTreeList	`json:"children"`
}

func GetTreeMenu(menuList *[]models.MenuObj) LeftMenuJson{
	var data LeftMenuJson
	data.HomeInfo = HomeInfoJson{"首页","/admin/index"}
	data.LogoInfo = LogoInfoJson{"BIN ADMIN","","http://r3og2zjrv.hb-bkt.clouddn.com/logo.png"}

	data.MenuInfo = getMenuRecursive(menuList,0)

	return data
}

// GetMenuRecursive 递归获取树形菜单
func getMenuRecursive(menuList *[]models.MenuObj,pid int) []*TreeList {
	var treeList  []*TreeList

	var tmpMenu []Menu
	for _,s := range *menuList{
		if s.PId == pid{
			tmpMenu = append(tmpMenu,Menu{s.Id,s.Title,s.Icon,s.Href,s.Target})
		}
	}

	for _, v := range tmpMenu{
		child := getMenuRecursive(menuList,v.Id)
		node := &TreeList{
			Id : v.Id,
			Target:v.Target,
			Title:v.Title,
			Icon:v.Icon,
			Href:v.Href,
		}
		node.Child = child
		treeList = append(treeList, node)
	}

	return treeList
}

// GetAuthMenuRecursive 递归获取树形菜单
func GetAuthMenuRecursive(menuList *[]models.MenuObj,pid int,menuAuthMap map[int]int) []*AuthTreeList {
	var treeList  []*AuthTreeList

	var tmpMenu []Menu
	for _,s := range *menuList{
		if s.PId == pid{
			tmpMenu = append(tmpMenu,Menu{s.Id,s.Title,s.Icon,s.Href,s.Target})
		}
	}

	for _, v := range tmpMenu{
		child := GetAuthMenuRecursive(menuList,v.Id,menuAuthMap)
		checked := false
		if _, ok :=menuAuthMap[v.Id]; ok{
			checked = true
		}
		if child != nil {  // 括号不能去
			checked = false
		}
		node := &AuthTreeList{
			Id : v.Id,
			Title:v.Title,
			Checked:checked,
			Spread:false,
		}
		node.Children = child
		treeList = append(treeList, node)
	}

	return treeList
}
